const crypto = require('crypto');

function WXBizDataCrypt(appId, sessionKey) {
  this.appId = appId;
  this.sessionKey = sessionKey;
}

WXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) {
  // 检查 sessionKey, encryptedData 和 iv 是否存在
  if (!this.sessionKey || !encryptedData || !iv) {
    throw new Error('Missing sessionKey, encryptedData, or iv');
  }

  // base64 decode
  let sessionKey, encryptedBuffer, ivBuffer;
  try {
    sessionKey = Buffer.from(this.sessionKey, 'base64');
    encryptedBuffer = Buffer.from(encryptedData, 'base64');
    ivBuffer = Buffer.from(iv, 'base64');
  } catch (e) {
    console.error('Buffer conversion error:', e);
    throw new Error('Failed to convert inputs to Buffer');
  }

  try {
    // 解密
    const decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, ivBuffer);
    decipher.setAutoPadding(true);
    
    let decoded = decipher.update(encryptedBuffer, 'binary', 'utf8');
    decoded += decipher.final('utf8');
    
    decoded = JSON.parse(decoded);
  } catch (err) {
    console.error('Decryption error:', err);
    throw new Error('Illegal Buffer');
  }

  // 检查解密后的数据中是否包含正确的 appId
  if (decoded.watermark && decoded.watermark.appid !== this.appId) {
    throw new Error('Illegal Buffer: appId mismatch');
  }

  return decoded;
}

module.exports = WXBizDataCrypt;
